<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="司机所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="1.2">
        <el-input v-model.trim="query.param" style="width: 300px;" placeholder="请输入" clearable>
          <el-select slot="prepend" v-model="qtype" style="width: 140px;" placeholder="请选择">
            <el-option label="绑定司机编号" value="driverCode" />
            <el-option label="绑定司机姓名" value="driverName" />
            <el-option label="值班司机编号" value="dutyDriverCode" />
            <el-option label="值班司机姓名" value="dutyDriverName" />
            <el-option label="值班押运员编号" value="escortCode" />
            <el-option label="值班押运员姓名" value="escortName" />
          </el-select>
        </el-input>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50202,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>

    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <el-dialog
      v-el-drag-dialog
      title="一键切换绑定司机"
      :visible.sync="visible"
      width="824px"
      @closed="reset"
    >
      <el-descriptions title="原司机信息" size="medium" :column="2" :label-style="labelStyle" :content-style="contentStyle">
        <el-descriptions-item label="原司机所属机构" style="width: 50%;">{{ dataForm.orgName }}</el-descriptions-item>
        <el-descriptions-item label="原司机">{{ dataForm.driverName }}</el-descriptions-item>
      </el-descriptions>
      <h3 style="color: #303133;">新司机信息</h3>
      <el-form ref="dataForm" class="form" :model="dataForm" :rules="rules" label-position="left">
        <el-form-item label="新司机所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="dataForm.orgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': false,
              'filterable': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChangeNew"
            @select-clear="selectClearable"
          />
        </el-form-item>
        <el-form-item label="新司机:" prop="newDriverCode">
          <el-select v-model="dataForm.newDriverCode" filterable placeholder="请选择">
            <el-option
              v-for="item in driverList"
              :key="item.userCode"
              :label="item.userName"
              :value="item.userCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="danger" @click="cancel('dataForm')">
          取消
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="sumbit('dataForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <cartDriverDetail ref="cartDriverDetail" />
  </div>
</template>

<script>
  import {
    queryBindDriverList,
    csDeliverUserList,
    changeBindcsmDriver,
    unBindcsmDriver
  } from '@/api'
  import { parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import cartDriverDetail from './components/cartDriverDetail'
  export default {
    name: '',
    components: {
      cartDriverDetail
    },
    data() {
      return {
        treeData: [],
        qtype: null,
        operatorActionMap: [],
        query: {
          orgSNNo: null,
          param: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        visible: false,
        driverList: [],
        dataForm: {
          orgSNNo: '',
          driverCode: '',
          driverName: '',
          newDriverCode: ''
        },
        rules: {
          orgSNNo: [{ required: true, message: '请选择机构', trigger: 'change' }],
          newDriverCode: [{ required: true, message: '请选择司机', trigger: 'change' }]
        },
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '绑定司机编号',
            prop: 'driverCode',
            width: 110
          },
          {
            label: '绑定司机',
            prop: 'driverName'

          },
          {
            label: '司机所属机构',
            prop: 'orgName',
            showOverflowTooltip: true
          },
          {
            label: '用户数量',
            prop: 'csmTotalCount',
            width: 80,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row)}>{row.csmTotalCount}</el-link>
          )
          },
          {
            label: '50型押金用户数',
            prop: 'csmCount1',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 1)}>{row.csmCount1}</el-link>
          )
          },
          {
            label: '非50型押金用户',
            prop: 'csmCount2',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 2)}>{row.csmCount2}</el-link>
          )
          },
          {
            label: '无押金用户数',
            prop: 'csmCount3',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 3)}>{row.csmCount3}</el-link>
          )
          },
          {
            label: '混合型用户数',
            prop: 'csmCount4',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openDetail(row, 4)}>{row.csmCount4}</el-link>
          )
          },
          { label: '值班司机编号',
            prop: 'dutyDriverCode'
          },
          { label: '值班司机',
            prop: 'dutyDriverName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.dutyDriverName ? <span style = { !row.orderReceiver ? 'color:#04CDC1' : ''}>{!row.orderReceiver ? `${row.dutyDriverName}（接单）` : `${row.dutyDriverName}`}</span> : <span></span>
            )
          },
          { label: '值班押运员编号',
            prop: 'escortCode'
          },
          { label: '值班押运员',
            prop: 'escortName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.escortName ? <span style = { row.orderReceiver ? 'color:#04CDC1' : ''}>{row.orderReceiver ? `${row.escortName}（接单）` : `${row.escortName}`}</span> : <span></span>
            )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 200,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                    v-permission={[50202, 2]}
                    underline={false}
                    size='mini'
                    onClick={() => this.bind(row, $index)}
                  >
                    一键切换绑定司机
                  </el-link>
                  <el-link
                    v-permission={[50202, 3]}
                    underline={false}
                    size='mini'
                    type='danger'
                    onClick={() => this.noBind(row, $index)}
                  >
                    一键解绑
                  </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      this.getTreeData()
    },
    beforeDestroy() {
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      // 切换司机选择所属机构
      async selectTreeChangeNew(value) {
        this.driverList = []
        // this.dataForm.orgId = value.orgId
        // this.dataForm.orgName = value.orgName
        const res = await csDeliverUserList({ deliveryOrgId: value.orgId, utype: 8388640 })
        if (res.data) {
          this.driverList = res.data.filter(item => item.userCode !== this.dataForm.driverCode)
        }
      },
      selectClearable() {
        this.dataForm.newDriverCode = ''
        this.driverList = []
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              if (key === 'timeRange') {
                if (obj['timeRange'].length > 0) {
                  query['createTimeStart'] = parseTime(obj[key][0], '{y}-{m}-{d} {h}:{i}:{s}')
                  query['createTimeEnd'] = parseTime(obj[key][1], '{y}-{m}-{d} {h}:{i}:{s}')
                }
              } else {
                query[key] = obj[key]
              }
            }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const res = await queryBindDriverList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      search() {
        if (!this.qtype && this.query.param) {
          this.$message.warning('请选择查询条件')
          return
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打开详情
      async openDetail(row, type) {
        await this.$refs.cartDriverDetail.open(row, type)
      },
      // 切换绑定司机
      async bind(row) {
        this.dataForm.driverName = row.driverName
        this.dataForm.driverCode = row.driverCode
        this.dataForm.orgSNNo = row.orgSNNo
        this.dataForm.orgId = row.orgId
        this.dataForm.orgName = row.orgName
        await this.selectTreeChangeNew(row)
        this.visible = true
      },
      // 解绑
      noBind(row) {
        this.$confirm(`此操作会将机构<strong style="color:red">${row.orgName}</strong>下的司机<strong style="color:red">${row.driverName}</strong>绑定的所有用户释放，今后这些用户就不属于该司机, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          unBindcsmDriver({ driverCode: row.driverCode }).then(res => {
            this.$notify({
              title: '提示',
              message: '解绑成功!',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解绑'
          })
        })
      },
      // 取消
      async cancel(formName) {
        await this.reset()
        this.visible = false
      },
      // 保存
      sumbit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = {
              driverCode: this.dataForm.driverCode,
              newDriverCode: this.dataForm.newDriverCode
            }
            console.log(form)
            changeBindcsmDriver(form).then(res => {
              this.$notify({
                title: '提示',
                message: '切换成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.$refs.lbTable.fetch()
            }).catch(err => {
              // this.$message.error(err.message)
              console.log(err)
              this.visible = false
            })
          } else {
            return false
          }
        })
      },
      reset() {
        this.$refs.dataForm.resetFields()
        this.driverList = []
        this.dataForm = {
          orgSNNo: '',
          driverCode: null,
          newDriverCode: null
        }
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7) {
          return 'danger-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    display: flex;
    width: 50%;
    padding-right: 10px;
    // .el-form-item__content {
    //   width: 100%;
    // }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}

</style>
